//
//  HSYHomeViewController.m
//  HSY
//
//  Created by 陈浩 on 2017/4/1.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "HSYHomeViewController.h"
#import "HSYHomeHeaderView.h"
#import "HSYHomeCollectionViewCell.h"
#import "HSYHomeCollectionHeaderView.h"
#import "HSYHelpViewController.h"
#import "HSYLoginViewController.h"
#import "HSYBaseWebViewController.h"
#import "HSYFillInformationViewController.h"
#import "HSYShopPhotosViewController.h"
#import "HSYCorporateInformationViewController.h"
#import "HSYAccountInformationViewController.h"
#import "HSYBalanceViewController.h"
#import "HSYBillViewController.h"
#import "HSYAdModel.h"
#import "HSYGetAdListRequest.h"
#import "UIImage+Tools.h"

static float kHeaderHeight = 207.0;
static float kBottomTabBarHegith = 49.0;
static CGFloat kHomeCollectionHeaderViewHegith = 115.0;

static NSString *const cellReuseIdentifier = @"cellReuseIdentifier";
static NSString *const headerReuseIdentifier = @"cellReuseIdentifier";


@interface HSYHomeViewController ()<UICollectionViewDelegateFlowLayout, HSYHomeHeaderViewDelegate, XRCarouselViewDelegate>{
    HSYHomeHeaderView *_headerView;
    __weak HSYHomeCollectionHeaderView *_collectionViewHeaderView;
}

@property (nonatomic, copy) NSArray *dataList;
@property (nonatomic, copy) NSArray *ads;

@end

@implementation HSYHomeViewController

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dataList = @[@{@"image":@"loan",@"title":@"贷款申请"},
                      @{@"image":@"Credit",@"title":@"信用卡申请"},
                      @{@"image":@"more",@"title":@"持续加入"}]; //展示信息数据源
    
    [self reloadHeaderView]; //设置头部视图
    [self setupCollectionView]; //设置collectionView的cell布局
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appReviewStateChanged) name:kNotificationReViewSuccess object:nil]; //查看完是否为正在审核中的APP版本，重新布局
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshBalance:) name:kNotificationRefreshBalance object:nil]; //更新余额
    
    [self loadAds];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    self.navigationController.navigationBar.shadowImage = nil;
    
    //如果用户已登录，请求账户信息
    if ([HSYUserCenter instatce].appAuUser.uid.length) {
        [[HSYUserCenter instatce] getBalanceSuccess:nil failure:nil];
    }
}

#pragma mark - methods -

//排序ads
- (void)sortAds:(NSArray *)ads{
    NSComparator cmptr = ^(HSYAdModel * obj1, HSYAdModel * obj2){
        if (obj1.viewOrder > obj2.viewOrder) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if (obj1.viewOrder < obj2.viewOrder) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };

    self.ads = [ads sortedArrayUsingComparator:cmptr];
}

//显示ads
- (void)reloadAds{
    if (_collectionViewHeaderView) {
        NSMutableArray *arr = [@[] mutableCopy];
        if (self.ads.count > 0) {
            for (HSYAdModel *model in self.ads) {
                [arr addObject:model.iconUrl];
            }
        }else{
            [arr addObjectsFromArray:@[[UIImage imageNamed:@"banner-hsy"]]];
        }
        _collectionViewHeaderView.carouselView.imageArray = [arr copy];
    }
}

//加载ads
- (void)loadAds{
    HSYGetAdListRequest *task = [[HSYGetAdListRequest alloc] init];
    __weak typeof(self) weakSelf = self;
    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            NSArray *ads = [HSYAdModel mj_objectArrayWithKeyValuesArray:response.encryptDataResult];
            [weakSelf sortAds:ads];
            [weakSelf reloadAds];
        }
    } failure:nil];
}

//appstore审核通过后重新布局
- (void)appReviewStateChanged{
    [self reloadHeaderView]; //重新生成头部视图
    
    //修改collectionView的背景颜色
    BOOL appIsInView = [[APPCenter defaultCenter] isInReview];
    self.collectionView.backgroundColor = appIsInView ? [UIColor hsyDefaultBackgroudColor] : [UIColor whiteColor];
    
    [self.collectionView reloadData];

}

//刷新余额
- (void)refreshBalance:(NSNotification *)notifi{
    _headerView.accountLabel.text = [NSString stringWithFormat:@"￥%@",[HSYUserCenter instatce].totalAmount.length ? [HSYUserCenter instatce].totalAmount:@"0.00"];
}

//更新头部视图
- (void)reloadHeaderView{
    if (_headerView && _headerView.superview) { //如果当前已存在header，则先移除
        [_headerView removeFromSuperview];
        _headerView = nil;
    }
    
    BOOL appIsInView = [[APPCenter defaultCenter] isInReview];
    
    _headerView = [HSYHomeHeaderView headerViewIsDebug:appIsInView];
    _headerView.delegate = self;
    
    [self.view addSubview:_headerView];
    [_headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.height.mas_equalTo(kHeaderHeight);
    }];
}

//定义collecitonView的布局
- (void)setupCollectionView{
    UICollectionViewFlowLayout *flowLayout = (id)self.collectionView.collectionViewLayout;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.itemSize = CGSizeMake((ScreenWidth()-2)/3,(ScreenWidth()-2)/3);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.headerReferenceSize = CGSizeMake(ScreenWidth(),kHomeCollectionHeaderViewHegith);
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"HSYHomeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:cellReuseIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HSYHomeCollectionHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerReuseIdentifier];
    BOOL appIsInView = [[APPCenter defaultCenter] isInReview];

    self.collectionView.backgroundColor = appIsInView ? [UIColor hsyDefaultBackgroudColor] : [UIColor whiteColor];
}


#pragma mark- super methods -
- (UIEdgeInsets)hsy_collectionViewEdgeInsets{
    return UIEdgeInsetsMake(kHeaderHeight, 0, kBottomTabBarHegith, 0);
}

- (BOOL)hsy_allowPullUp{
    return NO;
}

- (BOOL)hsy_allowPullDown{
    return NO;
}

- (void)hsy_handlePullDownToLoadNew{
    dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 1 *NSEC_PER_SEC);
    dispatch_after(time, dispatch_get_main_queue(), ^{
        [self hsy_headerEndRefreshing];
    });

}


#pragma mark - push to ... -
//push to 余额
- (void)pushToBalance{
    HSYBalanceViewController *vc = [[HSYBalanceViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}

//push to 账单
- (void)pushToBill{
    HSYBillViewController *vc = [[HSYBillViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UICollectionViewDelegate & UICollectionViewDataSource & UICollectionViewDelegateFlowLayout -

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    BOOL appIsInView = [[APPCenter defaultCenter] isInReview];
    
    return appIsInView ? 0 : self.dataList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dict = self.dataList[indexPath.item];

    HSYHomeCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:cellReuseIdentifier forIndexPath:indexPath];
    
    item.imageView.image = [UIImage imageNamed:dict[@"image"]];
    item.titleLabel.text = dict[@"title"];
    
    return item;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        HSYHomeCollectionHeaderView *headerRV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerReuseIdentifier forIndexPath:indexPath];
        headerRV.carouselView.delegate = self;
        headerRV.carouselView.contentMode = UIViewContentModeScaleAspectFit;
        headerRV.carouselView.placeholderImage = [UIImage imageWithColor:[UIColor whiteColor] size:CGSizeMake(10, 10)]; //默认占位图为白色

        _collectionViewHeaderView = headerRV;
        
        [self reloadAds];
        return headerRV;
    }
    return nil;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {//申请贷款
        [self applyLoan];
    }
    
    if (indexPath.row == 1) { //信用卡申请
        [self applyCreditCard];
    }
    
    if (indexPath.row == 2) { //持续加入
        
    }
}


#pragma mark - XRCarouselViewDelegate -
- (void)carouselView:(XRCarouselView *)carouselView clickImageAtIndex:(NSInteger)index{
    UIViewController *vc;
    if (self.ads.count == 0) {
        vc = [[HSYHelpViewController alloc] init];
    }else{
        if (index >= self.ads.count) return;
        
        HSYAdModel *model = self.ads[index];
        vc = [[HSYBaseWebViewController alloc] initWithAddress:model.jumpUrl title:nil];
    }
    
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - HSYHomeHeaderViewDelegate -

- (void)hsy_homeHeaderView:(HSYHomeHeaderView *)homeHeaderView handleBillBtn:(UIButton *)btn{ //账单
    if ([self needLogin]) return;
    if ([self goToAuditIfNeed]) return;
    
    HSYLog(@"账单");
    [self pushToBill];
}
- (void)hsy_homeHeaderView:(HSYHomeHeaderView *)homeHeaderView handleBalanceBtn:(UIButton *)btn{ //余额
    if ([self needLogin]) return;
    if ([self goToAuditIfNeed]) return;
    
    HSYLog(@"余额");
    
    //还未绑定二维码
    if (![HSYUserCenter instatce].appAuUser.dealerID.length) {
        alert_alam(@"提示", @"您的商铺尚未绑定二维码，请绑定后查看");
        return ;
    }
    
    //push to Balance
    [self pushToBalance];
}
- (void)hsy_homeHeaderView:(HSYHomeHeaderView *)homeHeaderView handleCashBtn:(UIButton *)btn{ //收款
    if ([self needLogin]) return;
    if ([self goToAuditIfNeed]) return;
    
    [self showMessage:@"该功能暂未开通，敬请期待！"];
    HSYLog(@"收款");

}

- (void)hsy_homeHeaderView:(HSYHomeHeaderView *)homeHeaderView handleMessageBtn:(UIButton *)btn{ //消息按钮
    [self showMessage:@"该功能暂未开通，敬请期待！"];

}
- (void)hsy_homeHeaderView:(HSYHomeHeaderView *)homeHeaderView handleCustomerServiceBtn:(UIButton *)btn{ //点击客服按钮
    [self showMessage:@"该功能暂未开通，敬请期待！"];

}

#pragma mark - 是否需要登录 -

- (BOOL)needLogin{
    BOOL needLogin = [HSYUserCenter instatce].appAuUser.uid.length == 0;
    if (needLogin) {
        HSYLoginViewController *vc = [[HSYLoginViewController alloc] init];
        HSYBaseNavigationController *nav = [HSYBaseNavigationController navigtationControllerWithRootViewController:vc];
        
        [self.tabBarController presentViewController:nav animated:YES completion:nil];
    }
    return needLogin;
}

#pragma mark - 是否需要完善信息 -
- (BOOL)goToAuditIfNeed{
    if ([[HSYUserCenter instatce].appBizShop.status isEqualToString:@"3"] || [[HSYUserCenter instatce].appBizShop.status isEqualToString:@"4"]) {
        
        [self goAudit];
        return YES;
    }
    
    if ([[HSYUserCenter instatce].appBizShop.status isEqualToString:@"2"]) { //审核中
        alert_alam_cancel(@"提示", @"你的资料正在审核中，请在审核通过后在使用", @"确定");
        return YES;
    }
    
    return NO;
}

#pragma mark - 完善信息 -
- (void)goAudit{
    UIViewController *vc = nil;
    
    
    if ([HSYUserCenter instatce].appAuUser.auStep ==0) {
        vc = [[HSYFillInformationViewController alloc] init]; //填写店铺资料
    }
    
    if ([HSYUserCenter instatce].appAuUser.auStep ==1) {
        vc = [[HSYShopPhotosViewController alloc] init]; //店铺照片
    }
    
    if ([HSYUserCenter instatce].appAuUser.auStep ==2) {
        vc = [[HSYCorporateInformationViewController alloc] init]; //法人信息
    }
    
    if ([HSYUserCenter instatce].appAuUser.auStep ==3) {
        vc = [[HSYAccountInformationViewController alloc] init]; //结算信息
    }
    
    HSYBaseNavigationController *nav = [HSYBaseNavigationController navigtationControllerWithRootViewController:vc];
        
    [self.tabBarController presentViewController:nav animated:YES completion:nil];

}

#pragma mark - 附加的功能按钮 -
//信用卡申请
- (void)applyCreditCard{
    HSYBaseWebViewController *vc = [[HSYBaseWebViewController alloc] initWithAddress:@"http://channel.haodai.com/Mobile/creditcard/ref/hd_11015964/sid/haoshouyin001" title:@"信用卡申请"];
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}

//申请贷款
- (void)applyLoan{
    HSYBaseWebViewController *vc = [[HSYBaseWebViewController alloc] initWithAddress:@"https://loan.rongba.com/H5tuiguang/kff?ref=hd_11015964&sid=haoshouyin001" title:@"贷款申请"];
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
